<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Admin\Controller;

/**
 * 问题信息
 */
class ProblemController extends HomeController {

    public function _initialize(){
        parent::_initialize();
        $this->is_login();      //判断是否登录
    }

    //问题列表
	public function get_list(){
        $requestdata = file_get_contents("php://input");
        $paramData = json_decode($requestdata, true);
        $model = D("Problem");
        $field = "a.*,a.id as problem_id,DATE_FORMAT(FROM_UNIXTIME(a.create_time), '%Y-%m-%d %H:%i') as create_date";
        $result = $model->get_problem_list($paramData,$field);
        if($result['list']) {
            foreach ($result['list'] as $key => $val) {
                $val['answer_options'] = json_decode($val['answer_options'],true);
                $val['sort'] = intval($val['sort']);
                $result['list'][$key] = $val;
            }
        }
        $returnData = [
            'code' => 200,
            'data' => $result['list']?$result['list']:[],
            'total' => $result['count']
        ];
        echo json_encode($returnData);
    }


    //添加/修改问题
    public function save(){
        $requestdata = file_get_contents("php://input");
        $paramData = json_decode($requestdata, true);
        $model = D("Problem");
        if(empty($paramData['problem_name'])) $this->throw_exception('问题名称不能为空');
        if(empty($paramData['type'])) $this->throw_exception('类型不能为空');
        if(empty($paramData['sort'])) $this->throw_exception('排序不能为空');
        if(empty(is_int($paramData['sort']))) $this->throw_exception('排序只能是整数数字');
        if($paramData['sort'] > 999 || $paramData['sort'] < 0) $this->throw_exception('排序范围1~999');
        if($paramData['type'] != 1 && empty($paramData['answer_options'])) $this->throw_exception('答案选项不能为空');
        $paramData['userId'] =  $this->user_info['id'];
        $result = $model->problem_save($paramData);
        $this->throw_exception($result['msg'],$result['code']);
    }


    //客户问题答案
    public function get_problem_answer_list(){
        $requestdata = file_get_contents("php://input");
        $paramData = json_decode($requestdata, true);
        $model = D("ProblemAnswer");
        $result = $model->get_problem_answer_list($paramData);
        $returnData = [
            'code' => 200,
            'data' => $result['list']?$result['list']:[],
            'total' => $result['count']
        ];
        echo json_encode($returnData);
    }
}